package vn.com.shoppie.object;

import java.util.ArrayList;

import vn.com.shoppie.activity.R;
import vn.com.shoppie.sobject.Shop;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ProfileAdapter extends ArrayAdapter<Shop> {
	private ArrayList<Shop> mListShops;
	private LayoutInflater mInflater;
	public ProfileAdapter(Context context,
			ArrayList<Shop> objects) {
		super(context, R.layout.item_title_shop, objects);
		this.mListShops = objects;
		this.mInflater=LayoutInflater.from(context);
	}
	@Override
	public int getCount() {
		if(mListShops.size()%2==0) return mListShops.size()/2;
		else return mListShops.size()/2+1;
	}
	@Override
	public Shop getItem(int position) {
		return mListShops.get(position);
	}
	@Override
	public long getItemId(int position) {
		return (long)position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v=convertView;
		if(v==null) {
			ShopHolder _holder=new ShopHolder();
			v=this.mInflater.inflate(R.layout.item_title_shop, parent,false);
			_holder.shop1=(RelativeLayout)v.findViewById(R.id.ly_shop1);
			_holder.shop2=(RelativeLayout)v.findViewById(R.id.ly_shop2);
			_holder.avatar1=(ImageView)v.findViewById(R.id.iv_avatar_1);
			_holder.avatar2=(ImageView)v.findViewById(R.id.iv_avatar_2);
			_holder.title1=(TextView)v.findViewById(R.id.tv_title_1);
			_holder.title2=(TextView)v.findViewById(R.id.tv_title_2);
			_holder.score1=(TextView)v.findViewById(R.id.tv_score_1);
			_holder.score2=(TextView)v.findViewById(R.id.tv_score_2);
			_holder.pie1=(ImageButton)v.findViewById(R.id.btn_score_1);
			_holder.pie2=(ImageButton)v.findViewById(R.id.btn_score_2);
			
			v.setTag(_holder);
		}
		ShopHolder _holder=(ShopHolder)v.getTag();
		
		
		Shop item1=mListShops.get(2*position);
		Shop item2=null;
		
		if(mListShops.size()/2>position) {
			item2=mListShops.get(2*position+1);
		}
		fillShopToView(_holder,item1,item2);
		return v;
	}
	private void fillShopToView(ShopHolder holder,Shop item1,Shop item2) {
		if(item1!=null) {
			holder.avatar1.setImageResource(item1.idAvatarDef);
			holder.score1.setText(item1.score+"");
			holder.title1.setText(item1.title);
		}
		if(item2!=null) {
			holder.shop2.setVisibility(View.VISIBLE);
			holder.avatar2.setImageResource(item2.idAvatarDef);
			holder.score2.setText(item2.score+"");
			holder.title2.setText(item2.title);
		}else {
			holder.shop2.setVisibility(View.INVISIBLE);
		}
	}
	
	class ShopHolder{
		RelativeLayout shop1,shop2;
		ImageView avatar1,avatar2;
		TextView title1,title2;
		TextView score1,score2;
		ImageButton pie1,pie2;
		
	}
}